package com.play.ballen.home.ui

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.bumptech.glide.Glide
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.config.KVConst
import com.play.ballen.databinding.ActivityAddBottleBinding
import com.play.ballen.event.EventCost
import com.play.ballen.home.entity.BottlePutGaoji
import com.play.ballen.home.vm.PLPFragmentVM
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.GlobalConfiguration
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import com.qiniu.android.storage.UploadOptions
import com.yuven.appframework.util.MMKVUtil
import com.yuven.appframework.util.setOnSingleClickListener
import com.yuven.baselib.component.BaseMVVMActivity
import com.yuven.baselib.component.eventbus.Event
import com.yuven.baselib.component.eventbus.EventBusUtil
import com.yxp.permission.util.lib.PermissionUtil
import com.yxp.permission.util.lib.callback.PermissionResultCallBack
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.filter.Filter
import com.zhihu.matisse.internal.entity.CaptureStrategy
import com.zhihu.matisse.listener.OnCheckedListener
import com.zhihu.matisse.listener.OnSelectedListener
import java.io.File


class AddBottleActivity : BaseMVVMActivity<PLPFragmentVM, ActivityAddBottleBinding>() ,
    AMapLocationListener{
    private var mLocationClient: AMapLocationClient? = null //定位发起端

    private var mLocationOption: AMapLocationClientOption? = null //定位参数
    val REQUEST_CODE_CHOOSE = 10010

    private var longitude = 0.0
    private var latitude = 0.0
    private var uploadManager: UploadManager? = null
    private val token: String? = null
    private var keyname: String? = null
    private var list = arrayListOf<String>()
    var is_anonymous:Boolean = true
    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, AddBottleActivity::class.java)
            context.startActivity(starter)
        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_add_bottle
    }

    override fun viewModelClass(): Class<PLPFragmentVM> {
        return PLPFragmentVM::class.java
    }

    override fun registerEventBus(): Boolean {
        return true
    }

    override fun handleEvent(event: Event<Any>) {
        super.handleEvent(event)
        when (event.code) {
            EventCost.ADD_BOTTOLE_FACE -> {
                dataBinding.etDynamic.append(event.data.toString());
            }
        }
    }

    override fun initObserver() {
        super.initObserver()
        viewModel.actionAddSuccess.observe(this) {
            EventBusUtil.post(
                Event.create(
                    EventCost.RENG_BOTTLE_SUCCESS))
            finish()
        }

        viewModel.picToken.observe(this) {
            if(it!=null){
                selectPic()
            }
        }
    }

    private val onClickListener = tag@{ v: View ->
        when (v.id) {
            R.id.iv_smile -> {
                hideKeyboard(mContext)
                KeyboardActivity.start(mContext)
            }
        }
    }
    override fun initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dataBinding.ivBack.setOnClickListener{
            finish()
        }
        dataBinding.ivSmile.setOnSingleClickListener(onClickListener)
        //是否匿名
        dataBinding.checkbox.setOnCheckedChangeListener { _, isChecked ->
            is_anonymous = isChecked
        }


        dataBinding.tvPush.setOnClickListener{
//            if(!longitude.equals(0.0)){
                val bottlegaoji = BottlePutGaoji(
                    im = MMKVUtil.decodeInt(KVConst.IM,false)!!,
                    age_min = MMKVUtil.decodeInt(KVConst.AGE_MIN,false)!!,
                    age_max = MMKVUtil.decodeInt(KVConst.AGE_MAX,false)!!,
                    height_min = MMKVUtil.decodeInt(KVConst.HEIGHT_MIN,false)!!,
                    height_max = MMKVUtil.decodeInt(KVConst.HEIGHT_MAX,false)!!,
                    weight_min =  MMKVUtil.decodeInt(KVConst.WEIGHT_MIN,false)!!,
                    weight_max = MMKVUtil.decodeInt(KVConst.WEIGHT_MAX,false)!!,
                    shape =MMKVUtil.decodeInt(KVConst.SHAPE,false)!!,
                    other = MMKVUtil.decodeInt(KVConst.OTHER,false)!!,
                    is_block =  MMKVUtil.decodeBoolean(KVConst.IS_BLOCK, false),
                    city = MMKVUtil.decodeString(KVConst.CITY, false)?:""
                )

                val map = mutableMapOf<String, Any>()
                map["is_anonymous"] = is_anonymous
                map["content"] = dataBinding.etDynamic.text.toString()
                map["images"] = list
                map["is_like"] = MMKVUtil.decodeBoolean(KVConst.LAO_SHAIXUAN, false)==true
                if(MMKVUtil.decodeDouble(KVConst.LONG, false)!=0.00){
                    map["longitude"] = MMKVUtil.decodeDouble(KVConst.LONG, false)!!
                }else{
                    map["longitude"] = longitude
                }
                if(MMKVUtil.decodeDouble(KVConst.LAT, false)!=0.00){
                    map["latitude"] = MMKVUtil.decodeDouble(KVConst.LAT, false)!!
                }else{
                    map["latitude"] = latitude
                }
                map["vip_conf"] = bottlegaoji
                viewModel.putBottle(map)
//            }else{
//                getPermission()
//                ToastUtils.show("定位权限未获取")
//            }
        }

        dataBinding.ivAdd.setOnClickListener{
            getCameraPermission()

        }
        dataBinding.llTag.setOnClickListener{
//            val intent = Intent(this, BasicMapActivity::class.java)
//            intent.putExtra("key", "put");
//            startActivity(intent)
//            startActivityForResult(intent, MapActivity.REQUEST_CODE)
            ShaiXuanPutActivity.start(mContext)
        }

        dataBinding.etDynamic.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence?, i: Int, i1: Int, i2: Int) {
            }
            override fun onTextChanged(charSequence: CharSequence?, i: Int, i1: Int, i2: Int) {
            }
            override fun afterTextChanged(editable: Editable?) {
                dataBinding.tvNum.text = "${dataBinding.etDynamic.text.length}/120"
            }
        })
    }

    override fun initData() {
        getPermission()
    }



    override fun initIntent(intent: Intent?) {

    }

    private fun initLocation() {
        //初始化定位
        try {
            mLocationClient = AMapLocationClient(applicationContext)
            //设置定位回调监听
            mLocationClient!!.setLocationListener(this)
            //初始化定位参数
            mLocationOption = AMapLocationClientOption()
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption!!.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption!!.setNeedAddress(true)
            //设置是否只定位一次,默认为false
            mLocationOption!!.setOnceLocation(false)
            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationOption!!.setWifiActiveScan(true)
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            mLocationOption!!.setMockEnable(false)
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption!!.setInterval((6 * 1000).toLong())
            //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
            //给定位客户端对象设置定位参数
            mLocationClient!!.setLocationOption(mLocationOption)
            //启动定位
            mLocationClient!!.startLocation()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onLocationChanged(amapLocation: AMapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e(
                    "xypError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo()
                )
            }
            longitude = amapLocation.longitude
            latitude = amapLocation.latitude

            Log.e("xyp","longitude= "+longitude)
        }
    }

    private fun selectPic() {
        Matisse.from(this@AddBottleActivity)
            .choose(MimeType.ofImage(), false)
            .countable(true)
            .capture(true)
            .captureStrategy(
                CaptureStrategy(true, "com.play.ballen.fileprovider", "test")
            )
            .maxSelectable(1)
            .addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
            .gridExpectedSize(
                resources.getDimensionPixelSize(R.dimen.grid_expected_size)
            )
            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .thumbnailScale(0.85f)
            .imageEngine(GlideEngine())
            .setOnSelectedListener(OnSelectedListener { uriList: List<Uri?>?, pathList: List<String?> ->
                Log.e(
                    "onSelected",
                    "onSelected: pathList=$pathList"
                )
            })
            .showSingleMediaType(true)
            .originalEnable(true)
            .maxOriginalSize(10)
            .autoHideToolbarOnSingleTap(true)
            .setOnCheckedListener(OnCheckedListener { isChecked: Boolean ->
                Log.e(
                    "isChecked",
                    "onCheck: isChecked=$isChecked"
                )
            })
            .forResult(REQUEST_CODE_CHOOSE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            val result = Matisse.obtainResult(data)
            if (result != null && !result.isEmpty()) {
                updateImg(Matisse.obtainPathResult(data))
            }
        }
    }

    fun updateImg(path: List<String?>) {
        val file = File(path[0])
        // create RequestBody instance from file
        Log.i("xx", "file")
        Glide.with(mContext).load(file).into(dataBinding.ivImgOne)

        viewModel.picToken.value?.let { upload(it,file) }
    }
    private fun upload(uploadToken: String,file:File) {
        val startTime = System.currentTimeMillis()
        //配置断点续传
        /**
         * FileRecorder fileRecorder = null;
         * try {
         * fileRecorder = new FileRecorder("directory");
         * } catch (IOException e) {
         * e.printStackTrace();
         * }
         */
        //config配置上传参数
        var config: Configuration? = Configuration.Builder()
            .connectTimeout(90) // 链接超时。默认90秒
            .useHttps(true) // 是否使用https上传域名
//            .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
//            .resumeUploadVersion(Configuration.RESUME_UPLOAD_VERSION_V2) // 使用新版分片上传
            .concurrentTaskCount(3) // 并发上传线程数量为3
            .responseTimeout(90) // 服务器响应超时。默认90秒
//            .zone(FixedZone.zone0) // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
            .build()
        GlobalConfiguration.getInstance().isDnsOpen = false
        val uploadManager = UploadManager(config)
        val opt = UploadOptions(null, null, true,
            { key, percent -> Log.i("qiniutest", "percent:$percent") }, null
        )
        keyname += "test_" + startTime;
        uploadManager.put(file, keyname, uploadToken,
            UpCompletionHandler { key, info, res -> //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                if (info.isOK) {
                    Log.i("qiniu", "Upload Success")
                    val fileKey = res.getString("key")
                    val fileHash = res.getString("hash")
                    val width = res.getString("width")
                    val height = res.getString("height")
                    Log.d("xyp","File Key: $fileKey")
                    Log.d("xyp","File Hash: $fileHash")
                    list.clear()
                    list.add(fileKey)
//                    data1 = "ok"
//                    viewModel.addAvatar(fileKey,width,height)
                } else {
                    Log.i("qiniu", "Upload Fail")
                    //如果失败，这里可以把 info 信息上报自己的服务器，便于后面分析上传错误原因
                }
                Log.i("qiniu", "$key,\r\n $info,\r\n $res")
            }, null
        )
    }

    private fun getPermission() {
        val PERMISSIONS = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        PermissionUtil.getInstance().request(mActivity, PERMISSIONS,
            object : PermissionResultCallBack {
                override fun onPermissionGranted() {
                    initLocation()
                }

                override fun onPermissionGranted(vararg p0: String?) {
                }

                override fun onPermissionDenied(vararg p0: String?) {
                    toSelfSetting(mActivity)
                    ToastUtils.show("需要打开定位权限")
                }

                override fun onRationalShow(vararg p0: String?) {
                    toSelfSetting(mActivity)
                    ToastUtils.show("需要打开定位权限")
                }

            })
    }

    private fun getCameraPermission() {
        val PERMISSIONS = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
        )
        PermissionUtil.getInstance().request(mActivity, PERMISSIONS,
            object : PermissionResultCallBack {
                override fun onPermissionGranted() {
                    viewModel.getuploadToken()

                }

                override fun onPermissionGranted(vararg p0: String?) {
                }

                override fun onPermissionDenied(vararg p0: String?) {
//                    toSelfSetting(mActivity)
//                    ToastUtils.show("需要打开存储权限")
                }

                override fun onRationalShow(vararg p0: String?) {
//                    toSelfSetting(mActivity)
//                    ToastUtils.show("需要打开存储权限")
                }

            })
    }
    fun toSelfSetting(context: Context) {
        val mIntent = Intent()
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
            mIntent.data = Uri.fromParts("package", context.packageName, null)
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.action = Intent.ACTION_VIEW
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
            mIntent.putExtra("com.android.settings.ApplicationPkgName", context.packageName)
        }
        context.startActivity(mIntent)
    }

    fun hideKeyboard(context: Context?) {
        val activity = context as Activity?
        if (activity != null) {
            val imm = activity
                .getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm.isActive && activity.currentFocus != null) {
                imm.hideSoftInputFromWindow(
                    activity.currentFocus!!
                        .windowToken, 0
                )
            }
        }
    }
}